home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / BaseHTTPServer.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  22KB  |  503 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """HTTP server base class.
  5.  
  6. Note: the class in this module doesn't implement any HTTP request; see
  7. SimpleHTTPServer for simple implementations of GET, HEAD and POST
  8. (including CGI scripts).  It does, however, optionally implement HTTP/1.1
  9. persistent connections, as of version 0.3.
  10.  
  11. Contents:
  12.  
  13. - BaseHTTPRequestHandler: HTTP request handler base class
  14. - test: test function
  15.  
  16. XXX To do:
  17.  
  18. - log requests even later (to capture byte count)
  19. - log user-agent header and other interesting goodies
  20. - send error log to separate file
  21. """
  22. __version__ = '0.3'
  23. __all__ = [
  24.     'HTTPServer',
  25.     'BaseHTTPRequestHandler']
  26. import sys
  27. import time
  28. import socket
  29. from warnings import filterwarnings, catch_warnings
  30. catch_warnings().__enter__()
  31.  
  32. try:
  33.     import mimetools
  34. finally:
  35.     pass
  36.  
  37. import SocketServer
  38. DEFAULT_ERROR_MESSAGE = '<head>\n<title>Error response</title>\n</head>\n<body>\n<h1>Error response</h1>\n<p>Error code %(code)d.\n<p>Message: %(message)s.\n<p>Error code explanation: %(code)s = %(explain)s.\n</body>\n'
  39. DEFAULT_ERROR_CONTENT_TYPE = 'text/html'
  40.  
  41. def _quote_html(html):
  42.     return html.replace('&', '&').replace('<', '<').replace('>', '>')
  43.  
  44.  
  45. class HTTPServer(SocketServer.TCPServer):
  46.     allow_reuse_address = 1
  47.     
  48.     def server_bind(self):
  49.         '''Override server_bind to store the server name.'''
  50.         SocketServer.TCPServer.server_bind(self)
  51.         (host, port) = self.socket.getsockname()[:2]
  52.         self.server_name = socket.getfqdn(host)
  53.         self.server_port = port
  54.  
  55.  
  56.  
  57. class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
  58.     '''HTTP request handler base class.
  59.  
  60.     The following explanation of HTTP serves to guide you through the
  61.     code as well as to expose any misunderstandings I may have about
  62.     HTTP (so you don\'t need to read the code to figure out I\'m wrong
  63.     :-).
  64.  
  65.     HTTP (HyperText Transfer Protocol) is an extensible protocol on
  66.     top of a reliable stream transport (e.g. TCP/IP).  The protocol
  67.     recognizes three parts to a request:
  68.  
  69.     1. One line identifying the request type and path
  70.     2. An optional set of RFC-822-style headers
  71.     3. An optional data part
  72.  
  73.     The headers and data are separated by a blank line.
  74.  
  75.     The first line of the request has the form
  76.  
  77.     <command> <path> <version>
  78.  
  79.     where <command> is a (case-sensitive) keyword such as GET or POST,
  80.     <path> is a string containing path information for the request,
  81.     and <version> should be the string "HTTP/1.0" or "HTTP/1.1".
  82.     <path> is encoded using the URL encoding scheme (using %xx to signify
  83.     the ASCII character with hex code xx).
  84.  
  85.     The specification specifies that lines are separated by CRLF but
  86.     for compatibility with the widest range of clients recommends
  87.     servers also handle LF.  Similarly, whitespace in the request line
  88.     is treated sensibly (allowing multiple spaces between components
  89.     and allowing trailing whitespace).
  90.  
  91.     Similarly, for output, lines ought to be separated by CRLF pairs
  92.     but most clients grok LF characters just fine.
  93.  
  94.     If the first line of the request has the form
  95.  
  96.     <command> <path>
  97.  
  98.     (i.e. <version> is left out) then this is assumed to be an HTTP
  99.     0.9 request; this form has no optional headers and data part and
  100.     the reply consists of just the data.
  101.  
  102.     The reply form of the HTTP 1.x protocol again has three parts:
  103.  
  104.     1. One line giving the response code
  105.     2. An optional set of RFC-822-style headers
  106.     3. The data
  107.  
  108.     Again, the headers and data are separated by a blank line.
  109.  
  110.     The response code line has the form
  111.  
  112.     <version> <responsecode> <responsestring>
  113.  
  114.     where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
  115.     <responsecode> is a 3-digit response code indicating success or
  116.     failure of the request, and <responsestring> is an optional
  117.     human-readable string explaining what the response code means.
  118.  
  119.     This server parses the request and the headers, and then calls a
  120.     function specific to the request type (<command>).  Specifically,
  121.     a request SPAM will be handled by a method do_SPAM().  If no
  122.     such method exists the server sends an error response to the
  123.     client.  If it exists, it is called with no arguments:
  124.  
  125.     do_SPAM()
  126.  
  127.     Note that the request name is case sensitive (i.e. SPAM and spam
  128.     are different requests).
  129.  
  130.     The various request details are stored in instance variables:
  131.  
  132.     - client_address is the client IP address in the form (host,
  133.     port);
  134.  
  135.     - command, path and version are the broken-down request line;
  136.  
  137.     - headers is an instance of mimetools.Message (or a derived
  138.     class) containing the header information;
  139.  
  140.     - rfile is a file object open for reading positioned at the
  141.     start of the optional input data part;
  142.  
  143.     - wfile is a file object open for writing.
  144.  
  145.     IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
  146.  
  147.     The first thing to be written must be the response line.  Then
  148.     follow 0 or more header lines, then a blank line, and then the
  149.     actual data (if any).  The meaning of the header lines depends on
  150.     the command executed by the server; in most cases, when data is
  151.     returned, there should be at least one header line of the form
  152.  
  153.     Content-type: <type>/<subtype>
  154.  
  155.     where <type> and <subtype> should be registered MIME types,
  156.     e.g. "text/html" or "text/plain".
  157.  
  158.     '''
  159.     sys_version = 'Python/' + sys.version.split()[0]
  160.     server_version = 'BaseHTTP/' + __version__
  161.     default_request_version = 'HTTP/0.9'
  162.     
  163.     def parse_request(self):
  164.         '''Parse a request (internal).
  165.  
  166.         The request should be stored in self.raw_requestline; the results
  167.         are in self.command, self.path, self.request_version and
  168.         self.headers.
  169.  
  170.         Return True for success, False for failure; on failure, an
  171.         error is sent back.
  172.  
  173.         '''
  174.         self.command = None
  175.         self.request_version = version = self.default_request_version
  176.         self.close_connection = 1
  177.         requestline = self.raw_requestline
  178.         if requestline[-2:] == '\r\n':
  179.             requestline = requestline[:-2]
  180.         elif requestline[-1:] == '\n':
  181.             requestline = requestline[:-1]
  182.         
  183.         self.requestline = requestline
  184.         words = requestline.split()
  185.         if len(words) == 3:
  186.             (command, path, version) = words
  187.             if version[:5] != 'HTTP/':
  188.                 self.send_error(400, 'Bad request version (%r)' % version)
  189.                 return False
  190.             
  191.             try:
  192.                 base_version_number = version.split('/', 1)[1]
  193.                 version_number = base_version_number.split('.')
  194.                 if len(version_number) != 2:
  195.                     raise ValueError
  196.                 len(version_number) != 2
  197.                 version_number = (int(version_number[0]), int(version_number[1]))
  198.             except (ValueError, IndexError):
  199.                 version[:5] != 'HTTP/'
  200.                 version[:5] != 'HTTP/'
  201.                 self.send_error(400, 'Bad request version (%r)' % version)
  202.                 return False
  203.  
  204.             if version_number >= (1, 1) and self.protocol_version >= 'HTTP/1.1':
  205.                 self.close_connection = 0
  206.             
  207.             if version_number >= (2, 0):
  208.                 self.send_error(505, 'Invalid HTTP Version (%s)' % base_version_number)
  209.                 return False
  210.         elif len(words) == 2:
  211.             (command, path) = words
  212.             self.close_connection = 1
  213.             if command != 'GET':
  214.                 self.send_error(400, 'Bad HTTP/0.9 request type (%r)' % command)
  215.                 return False
  216.         elif not words:
  217.             return False
  218.         self.send_error(400, 'Bad request syntax (%r)' % requestline)
  219.         return False
  220.         self.command = command
  221.         self.path = path
  222.         self.request_version = version
  223.         self.headers = self.MessageClass(self.rfile, 0)
  224.         conntype = self.headers.get('Connection', '')
  225.         if conntype.lower() == 'close':
  226.             self.close_connection = 1
  227.         elif conntype.lower() == 'keep-alive' and self.protocol_version >= 'HTTP/1.1':
  228.             self.close_connection = 0
  229.         
  230.         return True
  231.  
  232.     
  233.     def handle_one_request(self):
  234.         """Handle a single HTTP request.
  235.  
  236.         You normally don't need to override this method; see the class
  237.         __doc__ string for information on how to handle specific HTTP
  238.         commands such as GET and POST.
  239.  
  240.         """
  241.         self.raw_requestline = self.rfile.readline()
  242.         if not self.raw_requestline:
  243.             self.close_connection = 1
  244.             return None
  245.         if not self.parse_request():
  246.             return None
  247.         mname = 'do_' + self.command
  248.         if not hasattr(self, mname):
  249.             self.send_error(501, 'Unsupported method (%r)' % self.command)
  250.             return None
  251.         method = getattr(self, mname)
  252.         method()
  253.  
  254.     
  255.     def handle(self):
  256.         '''Handle multiple requests if necessary.'''
  257.         self.close_connection = 1
  258.         self.handle_one_request()
  259.         while not self.close_connection:
  260.             self.handle_one_request()
  261.  
  262.     
  263.     def send_error(self, code, message = None):
  264.         '''Send and log an error reply.
  265.  
  266.         Arguments are the error code, and a detailed message.
  267.         The detailed message defaults to the short entry matching the
  268.         response code.
  269.  
  270.         This sends an error response (so it must be called before any
  271.         output has been generated), logs the error, and finally sends
  272.         a piece of HTML explaining the error to the user.
  273.  
  274.         '''
  275.         
  276.         try:
  277.             (short, long) = self.responses[code]
  278.         except KeyError:
  279.             (short, long) = ('???', '???')
  280.  
  281.         if message is None:
  282.             message = short
  283.         
  284.         explain = long
  285.         self.log_error('code %d, message %s', code, message)
  286.         content = self.error_message_format % {
  287.             'code': code,
  288.             'message': _quote_html(message),
  289.             'explain': explain }
  290.         self.send_response(code, message)
  291.         self.send_header('Content-Type', self.error_content_type)
  292.         self.send_header('Connection', 'close')
  293.         self.end_headers()
  294.         if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
  295.             self.wfile.write(content)
  296.         
  297.  
  298.     error_message_format = DEFAULT_ERROR_MESSAGE
  299.     error_content_type = DEFAULT_ERROR_CONTENT_TYPE
  300.     
  301.     def send_response(self, code, message = None):
  302.         '''Send the response header and log the response code.
  303.  
  304.         Also send two standard headers with the server software
  305.         version and the current date.
  306.  
  307.         '''
  308.         self.log_request(code)
  309.         if message is None:
  310.             if code in self.responses:
  311.                 message = self.responses[code][0]
  312.             else:
  313.                 message = ''
  314.         
  315.         if self.request_version != 'HTTP/0.9':
  316.             self.wfile.write('%s %d %s\r\n' % (self.protocol_version, code, message))
  317.         
  318.         self.send_header('Server', self.version_string())
  319.         self.send_header('Date', self.date_time_string())
  320.  
  321.     
  322.     def send_header(self, keyword, value):
  323.         '''Send a MIME header.'''
  324.         if self.request_version != 'HTTP/0.9':
  325.             self.wfile.write('%s: %s\r\n' % (keyword, value))
  326.         
  327.         if keyword.lower() == 'connection':
  328.             if value.lower() == 'close':
  329.                 self.close_connection = 1
  330.             elif value.lower() == 'keep-alive':
  331.                 self.close_connection = 0
  332.             
  333.         
  334.  
  335.     
  336.     def end_headers(self):
  337.         '''Send the blank line ending the MIME headers.'''
  338.         if self.request_version != 'HTTP/0.9':
  339.             self.wfile.write('\r\n')
  340.         
  341.  
  342.     
  343.     def log_request(self, code = '-', size = '-'):
  344.         '''Log an accepted request.
  345.  
  346.         This is called by send_response().
  347.  
  348.         '''
  349.         self.log_message('"%s" %s %s', self.requestline, str(code), str(size))
  350.  
  351.     
  352.     def log_error(self, format, *args):
  353.         '''Log an error.
  354.  
  355.         This is called when a request cannot be fulfilled.  By
  356.         default it passes the message on to log_message().
  357.  
  358.         Arguments are the same as for log_message().
  359.  
  360.         XXX This should go to the separate error log.
  361.  
  362.         '''
  363.         self.log_message(format, *args)
  364.  
  365.     
  366.     def log_message(self, format, *args):
  367.         """Log an arbitrary message.
  368.  
  369.         This is used by all other logging functions.  Override
  370.         it if you have specific logging wishes.
  371.  
  372.         The first argument, FORMAT, is a format string for the
  373.         message to be logged.  If the format string contains
  374.         any % escapes requiring parameters, they should be
  375.         specified as subsequent arguments (it's just like
  376.         printf!).
  377.  
  378.         The client host and current date/time are prefixed to
  379.         every message.
  380.  
  381.         """
  382.         sys.stderr.write('%s - - [%s] %s\n' % (self.address_string(), self.log_date_time_string(), format % args))
  383.  
  384.     
  385.     def version_string(self):
  386.         '''Return the server software version string.'''
  387.         return self.server_version + ' ' + self.sys_version
  388.  
  389.     
  390.     def date_time_string(self, timestamp = None):
  391.         '''Return the current date and time formatted for a message header.'''
  392.         if timestamp is None:
  393.             timestamp = time.time()
  394.         
  395.         (year, month, day, hh, mm, ss, wd, y, z) = time.gmtime(timestamp)
  396.         s = '%s, %02d %3s %4d %02d:%02d:%02d GMT' % (self.weekdayname[wd], day, self.monthname[month], year, hh, mm, ss)
  397.         return s
  398.  
  399.     
  400.     def log_date_time_string(self):
  401.         '''Return the current time formatted for logging.'''
  402.         now = time.time()
  403.         (year, month, day, hh, mm, ss, x, y, z) = time.localtime(now)
  404.         s = '%02d/%3s/%04d %02d:%02d:%02d' % (day, self.monthname[month], year, hh, mm, ss)
  405.         return s
  406.  
  407.     weekdayname = [
  408.         'Mon',
  409.         'Tue',
  410.         'Wed',
  411.         'Thu',
  412.         'Fri',
  413.         'Sat',
  414.         'Sun']
  415.     monthname = [
  416.         None,
  417.         'Jan',
  418.         'Feb',
  419.         'Mar',
  420.         'Apr',
  421.         'May',
  422.         'Jun',
  423.         'Jul',
  424.         'Aug',
  425.         'Sep',
  426.         'Oct',
  427.         'Nov',
  428.         'Dec']
  429.     
  430.     def address_string(self):
  431.         '''Return the client address formatted for logging.
  432.  
  433.         This version looks up the full hostname using gethostbyaddr(),
  434.         and tries to find a name that contains at least one dot.
  435.  
  436.         '''
  437.         (host, port) = self.client_address[:2]
  438.         return socket.getfqdn(host)
  439.  
  440.     protocol_version = 'HTTP/1.0'
  441.     MessageClass = mimetools.Message
  442.     responses = {
  443.         100: ('Continue', 'Request received, please continue'),
  444.         101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'),
  445.         200: ('OK', 'Request fulfilled, document follows'),
  446.         201: ('Created', 'Document created, URL follows'),
  447.         202: ('Accepted', 'Request accepted, processing continues off-line'),
  448.         203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
  449.         204: ('No Content', 'Request fulfilled, nothing follows'),
  450.         205: ('Reset Content', 'Clear input form for further input.'),
  451.         206: ('Partial Content', 'Partial content follows.'),
  452.         300: ('Multiple Choices', 'Object has several resources -- see URI list'),
  453.         301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
  454.         302: ('Found', 'Object moved temporarily -- see URI list'),
  455.         303: ('See Other', 'Object moved -- see Method and URL list'),
  456.         304: ('Not Modified', 'Document has not changed since given time'),
  457.         305: ('Use Proxy', 'You must use proxy specified in Location to access this resource.'),
  458.         307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'),
  459.         400: ('Bad Request', 'Bad request syntax or unsupported method'),
  460.         401: ('Unauthorized', 'No permission -- see authorization schemes'),
  461.         402: ('Payment Required', 'No payment -- see charging schemes'),
  462.         403: ('Forbidden', 'Request forbidden -- authorization will not help'),
  463.         404: ('Not Found', 'Nothing matches the given URI'),
  464.         405: ('Method Not Allowed', 'Specified method is invalid for this server.'),
  465.         406: ('Not Acceptable', 'URI not available in preferred format.'),
  466.         407: ('Proxy Authentication Required', 'You must authenticate with this proxy before proceeding.'),
  467.         408: ('Request Timeout', 'Request timed out; try again later.'),
  468.         409: ('Conflict', 'Request conflict.'),
  469.         410: ('Gone', 'URI no longer exists and has been permanently removed.'),
  470.         411: ('Length Required', 'Client must specify Content-Length.'),
  471.         412: ('Precondition Failed', 'Precondition in headers is false.'),
  472.         413: ('Request Entity Too Large', 'Entity is too large.'),
  473.         414: ('Request-URI Too Long', 'URI is too long.'),
  474.         415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
  475.         416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'),
  476.         417: ('Expectation Failed', 'Expect condition could not be satisfied.'),
  477.         500: ('Internal Server Error', 'Server got itself in trouble'),
  478.         501: ('Not Implemented', 'Server does not support this operation'),
  479.         502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
  480.         503: ('Service Unavailable', 'The server cannot process the request due to a high load'),
  481.         504: ('Gateway Timeout', 'The gateway server did not receive a timely response'),
  482.         505: ('HTTP Version Not Supported', 'Cannot fulfill request.') }
  483.  
  484.  
  485. def test(HandlerClass = BaseHTTPRequestHandler, ServerClass = HTTPServer, protocol = 'HTTP/1.0'):
  486.     '''Test the HTTP request handler class.
  487.  
  488.     This runs an HTTP server on port 8000 (or the first command line
  489.     argument).
  490.  
  491.     '''
  492.     if sys.argv[1:]:
  493.         port = int(sys.argv[1])
  494.     else:
  495.         port = 8000
  496.     server_address = ('', port)
  497.     HandlerClass.protocol_version = protocol
  498.     httpd = ServerClass(server_address, HandlerClass)
  499.     sa = httpd.socket.getsockname()
  500.     print 'Serving HTTP on', sa[0], 'port', sa[1], '...'
  501.     httpd.serve_forever()
  502.  
  503.